package edu.ncsu.csc.ip.routing.dv.udp;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import edu.ncsu.csc.ip.routing.dv.udp.serialize.NodeSerializer;

/**
 * Class <code>ServerThread</code>
 * 
 * ReceiverThread enqueues the updated DVs received from neighbors.
 * 
 * @author Moin Ayazifar <mayazif@ncsu.edu>
 * @author Steven Elliott <sdelliot@ncsu.edu>
 * 
 */
public final class ServerThread extends Thread {

	final RouterRemote router;
	protected final DatagramSocket socket;

	public ServerThread(RouterRemote router) throws SocketException {
		super(router.localNode.getName()+"ReceiverThread");
		this.router = router;
		socket = new DatagramSocket(router.port);
	}

	public void run() {

		while (true) {

			byte[] buf = new byte[RouterRemote.MAX_PACKET_SIZE];
			try {
				// receive request
				DatagramPacket packet = new DatagramPacket(buf, buf.length);
				socket.receive(packet);
				// add request to queue.
				// make sure no wait happens here by using max size queue.
				router.updatedNeighborDvQueue.put(NodeSerializer
						.bytesToNode(buf));
			} catch (Exception e) {
				System.err.println("Exception occured receiving the dv list");
				e.printStackTrace();
			}

		}

	}

}
